/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package aic.faults;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.Detail;
import javax.xml.soap.DetailEntry;
import javax.xml.namespace.QName;
import java.util.Locale;
import javax.xml.soap.SOAPException;
import aic.beans.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class ItemUnavailableFaultFactory {

    public static ItemUnavailableFault createSOAPItemUnavailableFault(String pFaultActor, Item it) {

        SOAPFault newFault = null;

        try {
            MessageFactory messageFactory = null;
            messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
            SOAPMessage message = messageFactory.createMessage();
            SOAPBody body = message.getSOAPBody();
            SOAPFault fault = body.addFault();

            QName faultName = new QName(
                    SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE,
                    "Sender");
            fault.setFaultCode(faultName);

            fault.addFaultReasonText("Item is unavailable", Locale.US);
            fault.setFaultRole(pFaultActor);


            Detail detail = fault.addDetail();

            QName entryName = new QName("http://bittschen.net/aic", "item");
            DetailEntry entry = detail.addDetailEntry(entryName);

            JAXBContext context = JAXBContext.newInstance(Item.class);
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.marshal(it, entry);


            message.saveChanges();


            newFault = body.getFault();
        } catch (JAXBException ex) {
            Logger.getLogger(MessageTooLongFaultFactory.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SOAPException e) {
            System.out.println("Meine Exception" + e);
        }
        ItemUnavailableFault iEx = new ItemUnavailableFault(newFault);
        return iEx;

    }

}
